/**
 * Desenvolvido pela Fábrica de Software do CESUPA.
 * Todos os direitos reservados.
 */
package br.cesupa.fabsoft.nomedoprojeto.system.application;

import java.io.IOException;
import java.io.OutputStream;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * General operations used on web applications.
 *
 * @author Breno Leite
 */
public class CommonWebOperations {

    /**
     * Closes the session and destroys any object related to it.
     */
    public void logout() {
        try {
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().
                    getExternalContext().getSession(false);
            session.invalidate();
        } catch (IllegalStateException illegalStateException) {
        }
    }

    /**
     * Sends a file to the client through a request.
     *
     * @param bytes the file bytes to be sended
     * @param fileName the name of the file
     * @param mimeType the mime type of the file
     * @param facesContext current faces context
     */
    public synchronized void sendDataToDownload(final byte[] fileBytes,
            final String fileName, final String mimeType) {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse httpServletResponse = (HttpServletResponse) context.getResponse();
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        httpServletResponse.setContentLength(fileBytes.length);
        httpServletResponse.setContentType(mimeType);

        try {
            OutputStream outputStream = httpServletResponse.getOutputStream();
            outputStream.write(fileBytes);
            outputStream.flush();
            outputStream.close();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
